<?php
	set_time_limit(0);
	ini_set("memory_limit","3072M");
	$statsType = "stock";
	$viewStockCode = !isset($_GET['stockCode'])?"":$_GET['stockCode'];
	$statsType = $_GET['statsType'];
	$G_PERIOD = !isset($_GET['period'])?"1day":$_GET['period'];
	$G_lspl = !isset($_GET['lspl'])?5:$_GET['lspl'];
	// 最后出现交易数据回溯周期数
	$CONFIG_LAST_SIGNAL_PERIOD_LEN = (int)$G_lspl;
	
	
	$ANA_DIR_FILES = "C://qihuo_file//".$statsType."//"; // 创建分析数据文件路径
	// 原始数据路径
	if($statsType == "stock"){
		$DIR_FILES = "E://new_tdx//T0002//export//";  	
	}
	if($statsType == "forex"){
		$DIR_FILES = "E://T//MetaTrader5_Normal//MQL5//Files//BUOU//";
	}
	if($statsType == "btc"){
		$DIR_FILES = "C://qihuo_file//btc_export//";
	}
	
	
	$FILE_LIST = array();
	
	$DATE = 0;
	$OPEN = 1;
	$HIGH = 2;
	$LOW = 3;
	$CLOSE = 4;
	$RISE = 5;
	
	$CNT_BARS = 0;

	$BARS = array();
	$BAR = array(array());
	function initBar($beginIndex){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		$CNT_BARS = count($BARS)-1;
		$i = 0;
		if($beginIndex!=0) $i = $CNT_BARS - $beginIndex;
		// 过滤大于10日的停牌股
		$lastBar =  explode(",",$BARS[$CNT_BARS-2]);
		//echo $BARS[$CNT_BARS-2] . '__'.diffNowDay($lastBar[0]).'</br>';
		//if(strpos($BARS[$CNT_BARS-2],",") && diffNowDay($lastBar[0])>10) return;
		// 初始化BAR数据
		for(;$i<=$CNT_BARS;$i++){   
		//for(;$i<=0;$i++){   
			if(!strpos($BARS[$i],","))break;
			$info = explode(",",$BARS[$i]);	
		//	$_year = explode("/",$info[0]);	
		//	if($_year[0]<2009)continue;
			$BAR[$i][$DATE] = $info[0];
			$BAR[$i][$OPEN] = $info[1];
			$BAR[$i][$HIGH] = $info[2];
			$BAR[$i][$LOW] = $info[3];
			$BAR[$i][$CLOSE] = $info[4];
			if($i!=0){
				if($BAR[$i-1][$CLOSE]==0){
					$BAR[$i][$RISE] = round($BAR[$i][$CLOSE]*100,2);		
				} else {
					$BAR[$i][$RISE] = round((($BAR[$i][$CLOSE]-$BAR[$i-1][$CLOSE])/$BAR[$i-1][$CLOSE])*100,2);
				}
			} else {
				if($BAR[0][$OPEN]==0){
					$BAR[0][$RISE] = round($BAR[0][$CLOSE]*100,2);
				} else {
					$BAR[0][$RISE] = round((($BAR[0][$CLOSE]-$BAR[0][$OPEN])/$BAR[0][$OPEN])*100,2);	
				}
			}
		}	
		$CNT_BARS = $i-1;
	}
	
	function diffNowDay($day){
		$day = str_replace("/","-",$day);
		$nowDay = date('Y-m-d');
		$dayArr=explode("-",$day);
		$nowDayArr=explode("-",$nowDay);
		$d1=mktime(0,0,0,$dayArr[1],$dayArr[2],$dayArr[0]);
		$d2=mktime(0,0,0,$nowDayArr[1],$nowDayArr[2],$nowDayArr[0]);
		return round(($d2-$d1)/3600/24);
	}
	
	function getBarIndexByDate($date){
		$rst = -1;
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		for($i=$CNT_BARS;$i>=0;$i--){
			if($BAR[$i][$DATE]==$date){
				$rst = $i;
				break;
			}
		}
		return $rst;
	}
	
	$ema12 = array();
	$ema26 = array();
	$ema9 = array();
	// 指数平均移动
	function getEMA($price,$length,$shift){
		$fcactor = 2 / ($length + 1);
		if($shift==0){
			$GLOBALS['ema'.$length][0] = $price;
		} else {
			$GLOBALS['ema'.$length][$shift] = $GLOBALS['ema'.$length][$shift-1] + $fcactor * ($price - $GLOBALS['ema'.$length][$shift-1]); 	
		}
		return $GLOBALS['ema'.$length][$shift];
	}
	
	$macd_diff = array();
	$macd_avg = array();
	$macd = array();
	function initMacd($fastLength,$lowLength,$macdLength){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		Global $macd,$macd_diff, $macd_avg, $macd,$ema12,$ema26,$ema9;
		for($i=0;$i<=$CNT_BARS;$i++){   
			$macd[$i] = getEMA($BAR[$i][$CLOSE],$fastLength,$i)-getEMA($BAR[$i][$CLOSE],$lowLength,$i);
			$macd_avg[$i] = getEMA($macd[$i],$macdLength,$i);
			$macd_diff[$i] =($macd[$i] - $macd_avg[$i])*2;
		}
	}
		
	// N日内的最高价
	function highest($length,$shift,&$hIndex){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		$hRst = 0;
		if($shift == 0){
			$hIndex = 0;	
			$hRst = $BAR[0][$HIGH];
			return $hRst;
		}
		$len = $shift-$length;
		if($len<0)$len = 0;
		for($i=$shift;$i>$len;$i--){
			if($BAR[$i][$HIGH] > $hRst){
				$hRst = $BAR[$i][$HIGH];
				$hIndex = $i;
			}
		}
		$GLOBALS['highest'.$length][$shift] = $hRst;
		return $hRst;
	}
	
	// N日内的最低价
	function lowest($length,$shift,&$lIndex){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		$lRst = 9999;
		if($shift == 0){
			$lIndex = 0;	
			$lRst = $BAR[0][$LOW];
			return $lRst;
		}
		$len = $shift-$length;
		if($len<0)$len = 0;
		for($i=$shift;$i>$len;$i--){
			if($BAR[$i][$LOW] < $lRst){
				$lRst = $BAR[$i][$LOW];
				$lIndex = $i;
			}
		}
		$GLOBALS['lowest'.$length][$shift] = $lRst;
		return $lRst;
	}
	

	$rsv = array();
	$kdj_k = array();
	$kdj_d = array();
	$kdj_j = array();
	function initKdj($length,$lowLength,$moothLength){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		Global $rsv,$kdj_k,$kdj_d,$kdj_j;
		for($i=0;$i<=$CNT_BARS;$i++){  
			$hlDif = highest($length,$i,$hIndex)-lowest($length,$i,$lIndex);
			if($hlDif==0){
				$rst[$i] = 0;
			} else {
				$rsv[$i] = ($BAR[$i][$CLOSE]-lowest($length,$i,$lIndex))/$hlDif*100;
			}
			$kdj_k[$i] = getSma($rsv,$kdj_k,$lowLength,$i,1);
			$kdj_d[$i] = getSma($kdj_k,$kdj_d,$moothLength,$i,1);
			$kdj_j[$i] = 3*$kdj_k[$i] - 2*$kdj_d[$i];
		}
	}
	
	// 移动平均
	function getSma(&$price,&$pricePrev,$length,$shift,$weight){
		if($shift==0) return $rst = 50;	
		$len = $shift - $length;
		if($len<0)$len = 0;
		$rst = ($weight * $price[$shift] + $pricePrev[$shift-1]*($length-$weight))/$length;
		return $rst;
	}
	
	// 求N日标准差
	function getStandarDevForBoll($length,$shift){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		if($shift==0) return $BAR[$shift][$CLOSE];
		$len = $shift - $length ;
		if($len<0)$len = 0;
		$avg = 0;
		$sumSqr = 0;
		$rst = 0;
		for($i=$shift;$i>$len;$i--){
			$avg += $BAR[$i][$CLOSE];	
		}
		$avg = $avg/$length;
		for($i=$shift;$i>$len;$i--){
			$sumSqr = $sumSqr + pow($BAR[$i][$CLOSE]-$avg,2);
		}
		$rst = $sumSqr / ($length-1);
		if($rst >0)$rst = sqrt($rst);
		return $rst;
	}
	
	$boll = array();
	$boll_ub = array();
	$boll_lb = array();
	function initBoll($length,$offset){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		Global $boll,$boll_ub,$boll_lb;
		initMa($length);
		for($i=0;$i<=$CNT_BARS;$i++){  
			$boll[$i] = $GLOBALS['ma'.$length][$i];
			$std = getStandarDevForBoll($length,$i);
			$boll_ub[$i] = $boll[$i] + $offset * $std;
			$boll_lb[$i] = $boll[$i] - $offset * $std;
		}
	}
	
	$ma5 = array();
	$ma10 = array();
	function initMa($period){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE,$RISE;
		$sum = 0;
		for($i=$CNT_BARS;$i>=$period;$i--){   
			$sum = 0;
			for($n=$i;$n>=$i-$period+1;$n--){
				$sum += $BAR[$n][$CLOSE];
			}
			$GLOBALS['ma'.$period][$i] = round($sum/$period,0);
		}		
	}
	
	// 上穿
	function crossOver($price1,$price2,$shift){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE;
		$rst = false;
		if($price1[$shift] > $price2[$shift]){
			$count = $shift-1;
			$con = $price1[$shift] == $price2[$shift];
			while($con && $count >= 0){
				$count = $count -1;
				$con = $price1[$count] == $price2[$count];
			}
			if($price1[$count] < $price2[$count])
				$rst = true;
		} 
	
		return($rst);
	}
	
	// 下穿
	function crossUnder($price1,$price2,$shift){
		Global $BARS,$BAR,$CNT_BARS,$DATE,$OPEN,$HIGH,$LOW,$CLOSE;
		$rst = false;
		if($price1[$shift] < $price2[$shift]){
			$count = $shift-1;
			$con = $price1[$shift] == $price2[$shift];
			while($con && $count >= 0){
				$count = $count - 1;
				$con = $price1[$count] == $price2[$count];
			}
			if($price1[$count] > $price2[$count])
				$rst = true;
		} 
		return $rst;
	}
	
	function fileWrite($filePath,$content){
		$file_pointer = fopen($filePath,"w+");     
		fwrite($file_pointer,$content);
		fclose($file_pointer);
	}
	
	function getFileContentByFileName($fileName){
		Global $DIR_FILES,$G_PERIOD;
		$rst = "";
		$contents = "";
		$FILE_PATH = $DIR_FILES . $G_PERIOD . "//" . $fileName . ".txt";
		$fileSzie = filesize ($FILE_PATH);
		if($fileSzie>0){
			$handle = fopen($FILE_PATH, "r");
			$contents = fread($handle, filesize ($FILE_PATH));		
			fclose($handle);
		}
		if(strpos($contents,"00")==false && strpos($contents,"/")==false){
			echo 'empty================:'.$fileName.'</br>';
		} else {
			$rst = $contents;	
		}
		return $rst;
	}
	
	function getFixFileContentByFileName($fileName){
		Global $DIR_FILES,$G_PERIOD;
		$rst = "";
		$contents = getFileContentByFileName($fileName);
		//if($contents!=""){
			echo $fileName.'</br>';
			$contents = str_replace(".","",$contents);  
			$contents = iconv('GB2312', 'UTF-8', $contents);
			$contents = str_ireplace("数据来源:通达信","",$contents);  
			$rst = $contents;
			$FILE_PATH = $DIR_FILES . $G_PERIOD . "//" . $fileName . ".txt";
			fileWrite($FILE_PATH,$contents);
		//}
		return $rst;
	}
	
	function getFileList(){
		Global $DIR_FILES,$FILE_LIST,$ANA_DIR_FILES,$PAGE_MODEL,$G_PERIOD;
		// 先删除旧分析文件
		$delFileDir = $ANA_DIR_FILES.$PAGE_MODEL.'//' . $G_PERIOD . '//';
		echo '先删除旧分析文件：'.$delFileDir.'......';
		if (is_dir($delFileDir)){
			if ($dh = opendir($delFileDir)){
				echo '打开目录成功......';
				$i = 0;
				while (($fileName = readdir($dh))!= false)
					if(strpos($fileName,"buy.txt") || strpos($fileName,"sell.txt")){{
						$fullpath = $delFileDir . $fileName;
						$fullpath = str_replace("//","/",$fullpath); 
						unlink($fullpath);
					}
				}
				closedir($dh);
				echo '删除成功！</br>';
			} else {
				echo '打开目录失败！</br>';		
			}
		} else {
			echo '目录不存在！</br>';	
		}
		
		// 获取文件
		echo '获取原始数据文件名列表：'.$DIR_FILES. $G_PERIOD . '//......';
		$fileNamesDir = $DIR_FILES. '//' . $G_PERIOD . '//';
		if (is_dir($fileNamesDir)){
			if ($dh = opendir($fileNamesDir)){
				echo '打开目录成功......';		
				$i = 0;
				while (($fileName = readdir($dh))!= false){
					if(strpos($fileName,".txt")){
						$fileName = str_replace(".txt","",$fileName);  
						$FILE_LIST[$i] = $fileName;
						$i++;
					}
				}
				closedir($dh);
				echo '获取文件名成功！</br>';
			} else {
				echo '打开目录失败！</br>';		
			}
		} else {
			echo '目录不存在！</br>';	
		}
	}
	
	function mk_dir($path){ 
		if (!file_exists($path)){ 
			mk_dir(dirname($path)); 
			mkdir($path, 0777); 
		} 
	} 
?>
